from flask import Blueprint, request, jsonify, Response, stream_with_context
from services.text2sql_agent_service import Text2SQLAgentService
from typing import Dict, Any
import json
import asyncio

text2sql_bp = Blueprint('text2sql', __name__)
text2sql_service = Text2SQLAgentService()

@text2sql_bp.route('/process-query', methods=['POST'])
def process_text2sql_query():
    try:
        data = request.get_json()
        if not data or 'query' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少必要的查询参数'
            }), 400

        query = data['query']
        result = text2sql_service.process_text2sql_query(query)
        
        # 检查数据类型并进行相应的转换
        if result.get('data') is not None:
            if hasattr(result['data'], 'to_dict'):  # 如果是DataFrame
                result['data'] = result['data'].to_dict(orient='records')
            # 如果已经是list就不需要转换
            
        # 如果结果包含Plotly图形，将其转换为JSON
        if result.get('figure') is not None:
            result['figure'] = result['figure'].to_json()

        return jsonify(result)

    except Exception as e:
        import traceback
        error_msg = f"处理请求时发生错误: {str(e)}\n{traceback.format_exc()}"
        print(error_msg)  # 打印详细错误信息
        return jsonify({
            'status': 'error',
            'message': error_msg
        }), 500